package dao

import (
	"TTMS/model"
	"TTMS/utils"
	"fmt"
)

// AddMessage 添加新的评论
func AddMessage(message *model.Message) error {
	//写 sql 语句
	sqlStr := "insert into messages(film_name, content, sender_id, message_type, received_id, time) values (?,?,?,?,?,?)"
	//执行
	_, err := utils.DB.Exec(sqlStr, message.FilmName, message.Content, message.SenderID, message.MessageType, message.ReceivedID, message.Time)
	if err != nil {
		return err
	}
	return nil
}

// DeleteMessage 删除评论
func DeleteMessage(id int64) error {
	//写 sql 语句
	sqlStr := "delete from messages where id=?"
	//执行
	_, err := utils.DB.Exec(sqlStr, id)
	if err != nil {
		return err
	}
	return nil
}

// SelectMessageByTime 根据时间获取评论
func SelectMessageByTime(filmName string) ([]*model.Message, error) {
	//写 sql 语句
	sqlStr := "select id, film_name, content, sender_id, message_type, received_id, time from messages where film_name=? and message_type=? order by time desc"
	//执行
	rows, err := utils.DB.Query(sqlStr, filmName, 0)
	if err != nil {
		return nil, err
	}
	var messages []*model.Message
	for rows.Next() {
		message := &model.Message{}
		rows.Scan(&message.ID, &message.FilmName, &message.Content, &message.SenderID, &message.MessageType, &message.ReceivedID, &message.Time)
		message.Sender = GetUserByID(message.SenderID)
		message.Received, _ = GetMessageByAddresseeID(message.ID)
		messages = append(messages, message)
		for _, v := range message.Received {
			fmt.Println(v)
		}
	}
	return messages, nil
}

// UpdateMessageLike 更新评论的点赞量
func UpdateMessageLike(id, likeQuantity int64) error {
	//写 sql 语句
	sqlStr := "update messages set like_quantity=? where id=?"
	//执行
	_, err := utils.DB.Exec(sqlStr, likeQuantity, id)
	if err != nil {
		return err
	}
	return nil
}

// GetMessageByAddresseeID 获取某个用户收到的回复评论
func GetMessageByAddresseeID(messageID int64) ([]*model.Message, error) {
	//写 sql 语句
	sqlStr := "select id, film_name, content, sender_id, message_type, received_id, time from messages where (received_id=? and message_type=?) order by time desc"
	//执行
	rows, err := utils.DB.Query(sqlStr, messageID, 1)
	if err != nil {
		return nil, err
	}
	var messages []*model.Message
	for rows.Next() {
		message := &model.Message{}
		rows.Scan(&message.ID, &message.FilmName, &message.Content, &message.SenderID, &message.MessageType, &message.ReceivedID, &message.Time)
		message.Sender = GetUserByID(message.SenderID)
		messages = append(messages, message)
	}
	return messages, nil
}
